package cn.wolfcode.redis.impl;

import cn.wolfcode.domain.Rank;
import cn.wolfcode.redis.IRankRedisService;
import cn.wolfcode.redis.util.RedisKeys;
import cn.wolfcode.service.IRankService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Service
public class RankRedisServiceImpl implements IRankRedisService {
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private IRankService rankService;

    @Override
    public List<Rank> addRedis(Long id) {
        List<Rank> list = rankService.list();
        String key = RedisKeys.RANK_CODE.join(id.toString());
        Rank rank = null;
        if (!template.hasKey(key)) {//初始化
            for (Rank rank1 : list) {
                Long id1 = rank1.getId();
                String key1 = RedisKeys.RANK_CODE.join(id1.toString());
                template.opsForValue().set(key1, JSON.toJSONString(rank1));
            }
            rank = rankService.getById(id);
        } else {
            String rankStr = template.opsForValue().get(key);
            rank = JSON.parseObject(rankStr, Rank.class);
        }
        rank.setTotal(rank.getTotal() + 1);
        template.opsForValue().set(key, JSON.toJSONString(rank));

        List<Rank> total = new ArrayList<>();
        for (Rank rank1 : list) {
            Long id1 = rank1.getId();
            String key1 = RedisKeys.RANK_CODE.join(id1.toString());
            total.add(JSON.parseObject(template.opsForValue().get(key1), Rank.class));
        }
        total.sort(Comparator.comparingInt(Rank::getTotal).reversed());
        return total;
    }
}
